#!/usr/bin/perl -w

#=======================================================================
# mvdirnewest
# File ID: 41978dc8-fa51-11dd-ae34-000475e441b9
#
# Syntax: mvdirnewest directory
# Forandrer navnet på directoryen til den nyeste fila i trestrukturen under.
# Brukes til å lage orden i gamle versjoner av ting som ligger slengende rundt.
#
# Character set: UTF-8
# ©opyleft 1999– Øyvind A. Holm <sunny@sunbase.org>
# License: GNU General Public License version 2 or later, see end of 
# file for legal stuff.
#=======================================================================

use strict;
use Getopt::Long;

$| = 1;

our $Debug = 0;

our %Opt = (

    'debug' => 0,
    'file-rename' => 0,
    'help' => 0,
    'verbose' => 0,
    'version' => 0,

);

our $progname = $0;
$progname =~ s/^.*\/(.*?)$/$1/;
our $VERSION = "0.00";

Getopt::Long::Configure("bundling");
GetOptions(

    "debug" => \$Opt{'debug'},
    "file-rename|f" => \$Opt{'file-rename'},
    "help|h" => \$Opt{'help'},
    "verbose|v+" => \$Opt{'verbose'},
    "version" => \$Opt{'version'},

) || die("$progname: Option error. Use -h for help.\n");

$Opt{'debug'} && ($Debug = 1);
$Opt{'help'} && usage(0);
if ($Opt{'version'}) {
    print_version();
    exit(0);
}

die("Uferdig.\n");

my $RetVal = 0;

die("$progname: Unknown version of find(1) or program not found\n") unless (`find --version` =~ /GNU find/);

foreach (@ARGV) {
	$RetVal ||= process_dir($_);
}

exit $RetVal;

sub process_dir {
	my $dir_name = shift;
	unless (-e $dir_name) {
		warn("$progname: $dir_name: Directory not found\n");
		return;
	}
	unless (-d $dir_name) {
		if ($Opt{'file-rename'}) {
			my @stat_array;
			unless (@stat_array = stat($dir_name)) {
				warn("$progname: $dir_name: Can’t stat file: $!");
				return;
			}
			my $file_date = date2str($stat_array[9]);
			my $new_name = "$file_date.$dir_name";
			if (-e $new_name) {
				warn("$new_name: File already exists, won’t rename.\n");
			} else {

			}
		} else {
			warn("$progname: $dir_name: Not a directory. Need -f option to rename files.\n");
		}
		return;
	}
	my $newest_date = 0;
	my $newest_file = "";

	# FIXME: Dette med find er midlertidig (og kommer sikkert til å forbli her :)
	my @Files = `find $dir_name -type f`;
	unless (scalar @Files) {
		warn("$progname: $dir_name: No files found in directory\n");
		return;
	}
	foreach (@Files) {
		chomp;
		my $file_name = $_;
		my @stat_array;
		unless (@stat_array = stat($file_name)) {
			warn("$progname: $file_name: Can’t stat file: $!\n");
			return;
		}
		my $file_date = $stat_array[9];
		if ($file_date > $newest_date) {
			$newest_date = $file_date;
			$newest_file = $file_name;
		}
		# printf("$file_name: %s\n", date2str($file_date));
	}
	my $new_name = sprintf("%s.%s", date2str($newest_date), $dir_name);
	if (-e $new_name) {
		warn("$progname: $new_name: Directory entry already exists, skipping directory $dir_name");
		return;
	} else {
		# printf("Skulle til å rename(%s, %s)\n", $dir_name, $new_name);
		rename($dir_name, $new_name) || warn("$dir_name: Can’t rename directory to $new_name: $!");
		print("$progname: $dir_name → $new_name\n");
	}
	return(0);
} # process_dir()

sub rename_file {
	my ($From, $date_val) = @_;
	my $Date = date2str($date_val);
	my $To = "$Date.$From";

	unless (-e $To) {
		unless ($From =~ /^$Date/) {
			if (rename($From, $To)) {
				print("$From → $To\n");
			} else {
				warn("Error renaming \"$From\" to \"$To\": $!");
			}
		} else {
			warn("$From: Seems as file is already renamed. Entering coward mode.");
		}
	} else {
		warn("$To: File already exists, won’t rename $From\n");
	}
} # rename_file()

sub date2str {
	my @TA = gmtime(shift);
	return(sprintf("%04u%02u%02uT%02u%02u%02uZ", $TA[5]+1900, $TA[4]+1, $TA[3], $TA[2], $TA[1], $TA[0]));
} # date2str()

sub print_version {
    # Print program version {{{
    print("$progname v$VERSION\n");
    # }}}
} # print_version()

sub usage {
    # Send the help message to stdout {{{
    my $Retval = shift;

    if ($Opt{'verbose'}) {
        print("\n");
        print_version();
    }
    print(<<END);

Usage: $progname directory [directory [...]]

The program scans the underlying tree structure and renames the directory
to the date of the newest file.

Options:

  -f, --file-rename
    Allow files to be renamed.
  -h, --help
    Show this help.
  -v, --verbose
    Increase level of verbosity. Can be repeated.
  --version
    Print version information.
  --debug
    Print debugging messages.

END
    exit($Retval);
    # }}}
} # usage()

sub msg {
    # Print a status message to stderr based on verbosity level {{{
    my ($verbose_level, $Txt) = @_;

    if ($Opt{'verbose'} >= $verbose_level) {
        print(STDERR "$progname: $Txt\n");
    }
    # }}}
} # msg()

sub D {
    # Print a debugging message {{{
    $Debug || return;
    my @call_info = caller;
    chomp(my $Txt = shift);
    my $File = $call_info[1];
    $File =~ s#\\#/#g;
    $File =~ s#^.*/(.*?)$#$1#;
    print(STDERR "$File:$call_info[2] $$ $Txt\n");
    return("");
    # }}}
} # D()

__END__

# Plain Old Documentation (POD) {{{

=pod

=head1 NAME

mvdirnewest

=head1 SYNOPSIS

mvdirnewest directory [directory [...]]

=head1 DESCRIPTION

The program scans the underlying tree structure and renames the directory
to the date of the newest file.

=head1 OPTIONS

=over 4

=item B<-f>, B<--file-rename>

Allow files to be renamed.

=item B<-h>, B<--help>

Print a brief help summary.

=item B<-v>, B<--verbose>

Increase level of verbosity. Can be repeated.

=item B<--version>

Print version information.

=item B<--debug>

Print debugging messages.

=back

=head1 AUTHOR

Made by Øyvind A. Holm S<E<lt>sunny@sunbase.orgE<gt>>.

=head1 COPYRIGHT

Copyleft © Øyvind A. Holm E<lt>sunny@sunbase.orgE<gt>
This is free software; see the file F<COPYING> for legalese stuff.

=head1 LICENCE

This program is free software: you can redistribute it and/or modify it 
under the terms of the GNU General Public License as published by the 
Free Software Foundation, either version 2 of the License, or (at your 
option) any later version.

This program is distributed in the hope that it will be useful, but 
WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along 
with this program.
If not, see L<http://www.gnu.org/licenses/>.

=head1 SEE ALSO

=cut

# }}}

# vim: set fenc=UTF-8 ft=perl fdm=marker ts=4 sw=4 sts=4 et fo+=w :
